package com.zhuozhou.jdyc.main.base.activity;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.base.BaseActivity;
import com.zhuozhou.jdyc.base.BaseViewModel;
import com.zhuozhou.jdyc.databinding.WebViewBinding;

/**
 * Created by 方舟 on 2017/6/23
 */

public class WebViewActivity extends BaseActivity<BaseViewModel, WebViewBinding>{

    public final static String TITLE = "title_text";
    public final static String LOAD_URL = "load_url";
    private String url;
    @Override
    protected int getLayoutId() {
        return R.layout.web_view;
    }

    @Override
    public String setTitleBar() {
        return null;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initView() {
        WebSettings settings =  binding.webView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);
        settings.setTextZoom(100);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        settings.setAllowFileAccess(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        binding.webView.setWebViewClient(new MyWebViewClient());
        binding.webView.setWebChromeClient(new MyWebChromeClient());
        addMenu(R.menu.menu_browser, item -> {
            switch (item.getItemId()){
                case R.id.toolbar_browser:
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    break;
                case R.id.toolbar_copy:
                    // 获取系统剪贴板
                    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
                    ClipData clipData = ClipData.newPlainText("文件链接", url);
                    // 把数据集设置（复制）到剪贴板
                    clipboard.setPrimaryClip(clipData);
                    showToast("复制成功");
                    break;
            }
            return false;
        });
    }


    @Override
    public void initData(Bundle bundle) {
        url = bundle.getString(LOAD_URL);
        binding.webView.loadUrl(url);
    }


    /**
     * show the MainActivity
     *
     * @param context context
     */
    public static void show(Context context, String loadUrl, String title_text) {
        Intent intent = new Intent(context, WebViewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(LOAD_URL, loadUrl);//测试地址："file:///android_asset/protocol.html"
        bundle.putString(TITLE, title_text);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private static class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    //Web视图
    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                binding.progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                binding.progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                binding.progressBar.setProgress(newProgress);//设置进度值
            }
        }
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (binding.webView.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                binding.webView.goBack();
                return true;
            } else {//当webview处于第一页面时,直接退出程序
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
